package com.zhu.transaction.controller;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhu.transaction.mapper.SchoolMapper;
import com.zhu.transaction.pojo.*;
import com.zhu.transaction.pojo.state.*;
import com.zhu.transaction.service.*;
import com.zhu.transaction.utils.MyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpRequest;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

import static sun.plugin2.os.windows.FLASHWINFO.size;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhu
 * @since 2021-01-07
 */
@Controller
@RequestMapping("/order")
@Api(tags = "商品订单接口", description = "订单的增删改查")
public class OrderController {

    @Autowired
    ProductService productService;

    @Autowired
    UserService userService;

    @Autowired
    OrderService orderService;

    @Autowired
    FavoriteService favoriteService;

    @Autowired
    MessageService messageService;

    @Autowired
    SchoolMapper schoolMapper;

    @RequestMapping("/confirm")
    @ApiOperation(value = "确认订单信息", hidden = true)
    public String getProductDetail(@RequestParam(value = "productId", required = false) String productId,
                                   @RequestParam(value = "favoriteIds", required = false) String[] favoriteIds,
                                   Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<OrderItem> orderItemList = new ArrayList<>();
        float finallyTotalPrice = 0;

        //单件商品购买
        if (productId != null) {
            OrderItem orderItem = new OrderItem();
            List<Product> products = new ArrayList<>();
            Product productDetail = productService.getProductDetail(productId);
            if (productDetail != null && productDetail.getShelves()) {
                productDetail.setReleaseUserPojo(userService.getOneUserById(productDetail.getReleaseUser()));
                products.add(productDetail);
                orderItem.setProductList(products).setOrderId(MyUtils.createOrderId(user.getId(), products.get(0).getId())).setTotalPrice(productDetail.getPrice());
                orderItemList.add(orderItem);
                finallyTotalPrice += productDetail.getPrice();
            } else {
                model.addAttribute("message", "该商品已被卖家下架或删除");
                return "/common/error";
            }
        }

        //多件商品购买
        if (favoriteIds != null) {
            List<Product> favoriteProducts = productService.getFavoriteProducts(favoriteIds);
            Map<String, List<Product>> map = new HashMap<>();
            if (favoriteProducts == null || favoriteProducts.size() != favoriteIds.length) {
                model.addAttribute("message", "收藏的商品中含有被卖家删除的商品！");
                return "/common/error";
            }
            for (Product favoriteProduct : favoriteProducts) {
                if (!favoriteProduct.getShelves()) {
                    model.addAttribute("message", "收藏的商品中含有被卖家下架的商品！");
                    return "/common/error";
                }
                String releaseUserID = favoriteProduct.getReleaseUserPojo().getId();
                List<Product> releaseProducts = map.get(releaseUserID);
                if (releaseProducts == null) {
                    List<Product> products = new ArrayList<>();
                    products.add(favoriteProduct);
                    map.put(releaseUserID, products);
                } else {
                    releaseProducts.add(favoriteProduct);
                }
            }
            for (Map.Entry<String, List<Product>> orderMap : map.entrySet()) {
                OrderItem orderItem = new OrderItem();
                float totalPrice = 0;
                List<Product> products = orderMap.getValue();
                for (Product product : products) {
                    totalPrice += product.getPrice();
                }
                orderItem.setProductList(products).setOrderId(MyUtils.createOrderId(user.getId(), products.get(0).getId())).setTotalPrice(totalPrice);
                orderItemList.add(orderItem);
                finallyTotalPrice += orderItem.getTotalPrice();
            }
        }

        //处理学校信息
        List<SchoolDetail> schoolDetails = schoolMapper.queryAllSchool();
        List<SchoolCity> schoolData = new ArrayList<>();
        for (SchoolDetail schoolDetail : schoolDetails) {
            SchoolCity tmp = new SchoolCity();
            tmp.setCity(schoolDetail.getCity());
            String[] split = schoolDetail.getSchool().split(",");
            tmp.setSchoolName(Arrays.asList(split));
            schoolData.add(tmp);
        }


        model.addAttribute("schoolData", schoolData);
        model.addAttribute("orderItems", orderItemList);
        model.addAttribute("totalPrice", new BigDecimal(finallyTotalPrice).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue());
        model.addAttribute("favoriteIds", new Gson().toJson(favoriteIds));
        return "/main/order";
    }

    @RequestMapping("/payment")
    @ApiOperation(value = "支付页面", hidden = true)
    public String paymentSuccess(String orders, @RequestParam(value = "favoriteIds", required = false) String favoriteIds,
                                 String totalPrice, Model model, HttpSession session) throws UnsupportedEncodingException {

        Message message = new Message();

        //如果是从收藏中结算后，将收藏中结算的商品删除
        if (favoriteIds != null && !favoriteIds.equals("") && !favoriteIds.equals("null")) {
            List<String> favoriteList = new Gson().fromJson(favoriteIds, new TypeToken<List<String>>() {
            }.getType());
            favoriteService.cancelFavoriteProduct(favoriteList.toArray());
        }

        User user = (User) session.getAttribute("user");
        orders = URLDecoder.decode(orders, "UTF-8");
        List<Order> orderList = new Gson().fromJson(orders, new TypeToken<List<Order>>() {
        }.getType());
        //添加订单
        List<Order> orderListByOrderId = orderService.getOrderListByOrderId(orderList.get(0).getOrderId());
        if (orderListByOrderId.size() != 0) {
            model.addAttribute("message", "不能重复下单！");
            return "/common/error";
        }
        for (Order order : orderList) {
            order.setPurchaseUser(user.getId());
            message.setSendUser(user.getId());
            String messageContent = user.getRealName() + "在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "拍了你发布的商品" + order.getProductName() + ",请到个人中心的我的订单中查看详情。";
            message.setContent(messageContent).setReceiveUser(order.getReleaseUser()).setMessageType(2);
            messageService.addMessage(message);
            productService.updateProductState(order.getProductId(), ProductState.REMOVE);
            orderService.addOneOrder(order);
        }
        model.addAttribute("order", orderList.get(0));
        model.addAttribute("totalPrice", totalPrice);
        //如果是微信支付，返回相关信息(二维码地址,还有其他信息)
        if (orderList.get(0).getPurchaseWay() == 1) {
            Order orderTmp = orderList.get(0);
            Map map = orderService.createNative(orderTmp.getOrderId());
            model.addAttribute("qrcode", map);
            orderTmp.setQrcodeUrl(map.get("code_url").toString()).setQrcodeResult(map.get("result_code").toString());
            orderService.updatePayStatus(orderTmp);
        }
        //如果是支付宝支付
        if (orderList.get(0).getPurchaseWay() == 0) {
            try {
                String payForm = orderService.createPayForm(orderList.get(0).getOrderId(), totalPrice);
                model.addAttribute("payForm", payForm.substring(0, payForm.length() - 45));
            } catch (IOException e) {
                e.printStackTrace();
                model.addAttribute("message", e.getMessage());
                return "/common/error";
            }
        }
        return "/main/payment";
    }


    @RequestMapping("/paySuccess")
    public String paySuccess(String orderId, Model model) {
        BackState backState = orderService.updateOrderState(orderId, PaymentState.SUCCESS_PAYMENT, OrderTransactionState.WAITE_SEND);
        if (backState == BackState.SUCCESS) {
            List<Order> orderList = orderService.getOrderListByOrderId(orderId);
            Map<String, Integer> oldState = new HashMap<>();
            for (Order order : orderList) {
                //先保存之前的商品状态
                Product productDetail = productService.getProductDetail(order.getProductId());
                if (productDetail == null || !productDetail.getShelves()) {
                    //回退，将状态更新回去
                    orderService.updateOrderState(orderId, PaymentState.NO_PAYMENT, OrderTransactionState.WAITE_PAYMENT);
                    for (Order order2 : orderList) {
                        Integer oldProductState = oldState.get(order2.getProductId());
                        if (oldProductState != null)
                            productService.updateProductState(order2.getProductId(), oldProductState);
                    }
                    model.addAttribute("message", "商品被下架，购买失败！");
                    break;
                } else {
                    oldState.put(productDetail.getId(), productDetail.getProductState());
                    productService.updateProductState(order.getProductId(), ProductState.HAS_SALE);
                    model.addAttribute("order", orderList.get(0));
                }
            }
        }
        return "/main/success";
    }


    @ResponseBody
    @PostMapping("/deleteOrder")
    @ApiOperation(value = "删除订单")
    public R deleteOrder(String orderId, Boolean isBack, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Message message = new Message();
        //在订单没有完成之前，删除订单将商品重新加入列表中
        if (isBack) {
            List<Order> orderList = orderService.getOrderListByOrderId(orderId);
            for (Order order : orderList) {
                Product productDetail = productService.getProductDetail(order.getProductId());
                if (productDetail != null) {
                    //发送的人就是现在登录的人
                    message.setSendUser(user.getId());
                    if (productDetail.getProductState() == ProductState.REMOVE) {
                        String messageContent = user.getRealName() + "在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "取消购买了你发布的商品" + order.getProductName();
                        message.setContent(messageContent).setReceiveUser(order.getReleaseUser()).setMessageType(2);
                        messageService.addMessage(message);
                    }
                    productService.updateProductState(productDetail.getId(), ProductState.SALE);
                }
            }
        }
        BackState backState = orderService.deleteOrder(orderId);
        return backState == BackState.SUCCESS ? R.ok().message("操作成功") : R.error().message("操作失败");
    }


    @ResponseBody
    @PostMapping("/updateOrder")
    @ApiOperation(value = "更新订单状态")
    public R updateOrderState(String orderId, Boolean isSendProduct, HttpSession session) {
        Message message = new Message();
        User user = (User) session.getAttribute("user");

        BackState backState = orderService.updateOrderState(orderId, PaymentState.SUCCESS_PAYMENT, isSendProduct ? OrderTransactionState.BEING_SEND : OrderTransactionState.SUCCESS_TRANSACTION);
        if (backState == BackState.SUCCESS) {
            List<Order> orderList = orderService.getOrderListByOrderId(orderId);
            for (Order order : orderList) {
                message.setSendUser(user.getId());
                String messageContent = isSendProduct ?
                        user.getRealName() + "在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "给你购买的商品" + order.getProductName() + "发货了,请到个人中心的我的订单中查看详情。"
                        : user.getRealName() + "在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "收到了你的商品" + order.getProductName() + "并确认收货了,请到个人中心的我的订单中查看详情。";
                message.setContent(messageContent).setReceiveUser(isSendProduct ? order.getPurchaseUser() : order.getReleaseUser()).setMessageType(2);
                messageService.addMessage(message);
            }
        }

        return backState == BackState.SUCCESS ? R.ok().message("操作成功") : R.error().message("操作失败");
    }

    @ResponseBody
    @GetMapping("/queryPayStatus/{orderNo}")
    @ApiOperation(value = "查询订单支付状态(微信支付方式)")
    public R queryPayStatus(@PathVariable String orderNo) {
        Map<String, String> map = orderService.queryPayStatus(orderNo);
        if (map == null) {
            return R.error().message("支付失败");
        }
        if (map.get("trade_state").equals("SUCCESS")) {
            //添加支付记录,并更新订单表
            return R.ok().message("支付成功");
        }
        return R.ok().code(25000).message("请用微信扫一扫");
    }

    @GetMapping("/alipay/result")
    @ApiOperation(value = "查询订单支付状态(支付宝支付方式)")
    public String queryAlipayStatus(AliPayState aliPayState, Model model) {
        //验证是否支付成功
        Boolean result = orderService.aliPayReturnNotice(aliPayState);
        if (!result)
            model.addAttribute("message", "支付失败");
        return result ? "redirect:/order/paySuccess?orderId=" + aliPayState.getOut_trade_no() : "/common/error";
    }
}

